package com.zxf.appliction.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxf.appliction.domain.Article;
import com.zxf.appliction.domain.BootStrapPage;
import com.zxf.appliction.domain.Content;
import com.zxf.appliction.domain.Filesup;
import com.zxf.appliction.domain.Params;
import com.zxf.appliction.domain.Review;
import com.zxf.appliction.domain.Staffvo;
import com.zxf.appliction.domain.Users;
import com.zxf.appliction.service.FileService;
import com.zxf.appliction.service.ReviewService;
import com.zxf.appliction.service.UserService;
import com.zxf.appliction.util.DateJsonValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/review")
public class ReviewController {

	@Autowired
	private ReviewService reviewService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private FileService fileService;

	private static Logger logger = Logger.getLogger(ReviewController.class);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	private static JSONArray js = new JSONArray();

	public String login() {
		return "login";
	}

	/**
	 * 博客首页信息
	 * @param params
	 * @param author
	 * @param searchText
	 * @param title
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/saveReview")
	public @ResponseBody
	Map<String, Object> saveReview(Review review, HttpServletRequest request,
			HttpServletResponse response) {
		 Map<String,Object> responseMap = new HashMap<String,Object>();
		if(StringUtils.isBlank(review.getContent()) && null == review.getUserid()  && null == review.getArticleid()){
			 responseMap.put("method", "saveReview");  
		     responseMap.put("success", "false");  
		     responseMap.put("message", "参数为空！"); 
		}
		review.setAdddata(new Date());
		 responseMap.put("method", "saveReview");  
	     responseMap.put("success", "true");  
	     responseMap.put("message", "评论成功！"); 
		
		return responseMap;

	}


	
	
	/**
	 * 查看 文章信息
	 * @param articleID
	 * @param title
	 * @param request 
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailarticle")
	public ModelAndView detailarticle(String articleID, String title,
			HttpServletRequest request, HttpServletResponse response) {
		
		
		Article article = new Article();
	
		
		logger.info("article: "+article);
		
		ModelAndView modelAndView = new ModelAndView("post_detail");
		
		modelAndView.addObject("article", article);
		

		return modelAndView;
	}

	// 评论列表
	@RequestMapping(value = "/getReviewList", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject getReviewList(Params params, String searchText, String startime, String limit, String offset, String endtime,
			String channelid, Review review, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		int limits = 0;
		int start = 0;
		if (null != limit && limit != "")
			limits = Integer.parseInt(limit);
		if (null != offset && offset != "" && offset != "0")
			start = Integer.parseInt(offset);

		try {
			if (null != startime && !"".equals(startime)) {
				params.setStartdate(sdf.parse(startime));
			}
			if (null != endtime && !"".equals(endtime)) {
				params.setEnddate(sdf.parse(endtime));
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

		
		params.setLimit(limits);
		// 页码
		// 每页数量
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		int totle = reviewService.getReviewTotle(params, review);
		obj.put("total", totle); // 统计数量，这里写死10条

		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	@RequestMapping(value = "/getarticlelist.do")
	public @ResponseBody
	ModelAndView getarticlelist(HttpServletRequest request,
			HttpServletResponse response) {
		Users user;
		user = (Users) request.getSession().getAttribute("userInfo");
		ModelAndView modelAndView = new ModelAndView("webshow/index");
		modelAndView.addObject("user", user);

		return modelAndView;

	}

	@RequestMapping(value = { "/redisuserlist" })
	public @ResponseBody
	JSONObject redisuserlist(Params params, BootStrapPage temp, String limit,
			String start, Users users, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JsonConfig jsonConfig = new JsonConfig();

		// 每页数量
		int pageSize2 = 0;
		if (null != limit && limit != "") {
			pageSize2 = Integer.parseInt(limit);

		}

		List userlist = userService.getRedisUserList(params.getPage(),
				pageSize2);
		int totle = userService.getRedistotle("users");
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("rows", js.fromObject(userlist, jsonConfig));
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	// 用户列表
	@RequestMapping("/userlist")
	public @ResponseBody
	JSONObject userlist(Params params, String page, String limit, String start,
			String userid, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JsonConfig jsonConfig = new JsonConfig();
		// 页码
		int pageno = 1;
		if (null != page && !"".equals(page)) {
			pageno = Integer.parseInt(page);
		}
		pageno = params.getPage();
		// 每页数量
		int pageSize2 = Integer.parseInt(limit);
		int start2 = (pageno - 1) * pageSize2;
		// Map<String, Object> userlist2 = (Map<String, Object>)
		List userlist2 = userService.getUserList3(start2, pageSize2);
		int totle = userService.getusertotle();
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("rows", js.fromObject(userlist2, jsonConfig));
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}
	/**
	 * 博客首页信息
	 * @param params
	 * @param author
	 * @param searchText
	 * @param title
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/pictureIndex")
	public @ResponseBody
	ModelAndView pictureIndex(Params params, String author,String searchText, String title, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		params.setPagesize(5);
		String key = "3";
		Users user = userService.getUsers(key);
		
		
		//首页热门推荐文章列表
		List<Staffvo> hotFileslist = fileService.getFileListBytop(10);
		
		List<Staffvo> fileslist = fileService.getFileListByPagesizeAndPage(params, searchText);
		logger.info("fileslist:" + fileslist);
		int totalPages = fileService.getFileTotleByPagesizeAndPage(params, searchText);
        int nexPage = params.getPage() + 1;
        int prePage = params.getPage() - 1;
        
		ModelAndView modelAndView = new ModelAndView("pictureIndex");
		modelAndView.addObject("hotFileslist", hotFileslist);
		modelAndView.addObject("fileslist", fileslist);
		modelAndView.addObject("user", user);
		modelAndView.addObject("totalPages", totalPages);
		modelAndView.addObject("curPage", params.getPage());
		modelAndView.addObject("nexPage", nexPage);
		modelAndView.addObject("prePage", prePage);
		
		logger.info("totalPages:" + totalPages +" curPage:" + params.getPage() + " nexPage" + nexPage + " prePage" + prePage+" hotArticlelist:" + hotFileslist);
		long endTime = System.currentTimeMillis();
		logger.info("耗时:"+(endTime - startTime));
		return modelAndView;

	}
	/**
	 * 查看 文章信息
	 * @param articleID
	 * @param title
	 * @param request 
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailPicture")
	public ModelAndView detailPicture(Integer staffid,
			HttpServletRequest request, HttpServletResponse response) {
		
		
		Staffvo staffvo ;
		
       List<Filesup> filesupList ;
       String key = "3";
		Users user = userService.getUsers(key);

		// 取的图片信息
		staffvo = fileService.detailstaffvo(staffid);
		
		filesupList = fileService.getfilesupListByStaffid(staffid);
		
		
		
		logger.info("staffvo: "+staffvo +" filesupList:"+ filesupList);
		
		ModelAndView modelAndView = new ModelAndView("pictureDetail");
		
		modelAndView.addObject("staffvo", staffvo);
		modelAndView.addObject("filesupList", filesupList);
		modelAndView.addObject("user", user);
		

		return modelAndView;
	}
	
}
